import { Button, Modal, message, Spin } from 'antd';

const confirm = Modal.confirm;
import { WeaErrorPage, WeaTools, WeaAlertPage, WeaTab, WeaDialog, WeaNewScroll, WeaFormItem, WeaSearchGroup, WeaTextarea, WeaUpload, WeaInput, WeaError } from 'ecCom';
import { WeaTableNew, WeaSwitch } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';

const getKey = WeaTools.getKey;
import { WeaLocaleProvider } from 'ecCom';
import { isEmail } from '../../util/index';

const getLabel = WeaLocaleProvider.getLabel;

@observer
class AddressManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }
  componentDidMount() {
    const { contentStore, location: { query } } = this.props;
    contentStore.getViewAddressList(query);
    contentStore.getViewAddressRightMenu({ selectType: 'addressinfo', customerId: query.customerId });
  }
  componentWillUnmount() {
    // const {contentStore} = this.props;
    // contentStore.clearStatus();
  }
  render() {
    const { contentStore } = this.props;
    const { verified, hasRight, tableStore, operateAddressForm, operate, showModal } = contentStore;
    if (verified && !hasRight) {
      return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@ebofj4`} >
        <div style={{ color: '#000' }}>
          {getLabel(2012, '对不起，您暂时没有权限！')}
        </div>
      </WeaAlertPage>
      );
    }
    if (verified && hasRight) {
      return (
        <div style={{ height: '100%' }}>
          <WeaTable
            ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@ra9vtm`}
            comsWeaTableStore={tableStore}
            hasOrder
            needScroll
            onOperatesClick={this.onOperatesClick.bind(this)}
          />
          <WeaDialog
            ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@mrf47k`}
            style={{ width: 800, height: 480 }}
            visible={showModal}
            title={`${(operate === 'add' ? getLabel(611, '添加') : getLabel(93, '编辑')) + getLabel(110, '地址') + getLabel(87, '信息')}`}
            icon="icon-coms-crm"
            iconBgcolor="#96358a"
            buttons={this.getButtons()}
            onCancel={() => { operateAddressForm(false); }}
          >
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@illjl2`} height={'100%'}>
              {operate == 'add' ? this.getFormItems() : this.getEditForms()}
            </WeaNewScroll>
          </WeaDialog>
        </div>
      );
    }
    return <div />;
  }
    onOperatesClick = (record, index, operate, flag) => {
      const { customerId, deleteAddress, operateAddressForm } = this.props.contentStore;
      if (flag == '0') { // 编辑
        operateAddressForm(true, { customerId, addressId: record.randomFieldId }, 'edit');
      }
      if (flag == '1') { // 删除
        deleteAddress({ ids: record.randomFieldId });
      }
    }
    getButtons() {
      const { operate, operateAddressForm, saveAddress, loading } = this.props.contentStore;
      const btn = [];
      { operate == 'add' && btn.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@twbwbb@save`} type="primary" disabled={loading} onClick={() => { saveAddress(); }} >{getLabel(86, '保存')}</Button>); }
      btn.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vtvlh3@close`} onClick={() => operateAddressForm(false)}>{getLabel(309, '关闭')}</Button>);
      return btn;
    }
    getFormItems() {
      const { formCondition, form } = this.props.contentStore;
      const { isFormInit } = form;
      const group = [];
      const formParams = form.getFormParams();
      isFormInit && toJS(formCondition).map((c,indexGroup) => {
        const items = [];
        c.items.map((fields, index) => {
          let dom;
          let isunderline = '';
          if (fields.viewAttr == '1' || (fields.conditionType == 'BROWSER' && fields.browserConditionParam.viewAttr == '1')) { fields.hasBorder = false; isunderline = 'underline'; } // 只读样式控制
          if (fields.conditionType == 'UPLOAD') {
            const key = getKey(fields);
            const bindObj = form.$(key);
            dom = (<WeaUpload
              ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@h0ee2o@${index}`}
              {...bindObj.bind()}
              {...fields}
              {...fields.otherParams}
              uploadId={fields.domkey[0]}
              uploadUrl="/api/crm/common/fileUpload"
              category="0,0,0"
              autoUpload
              showBatchLoad={false}
              showClearAll={false}
              multiSelection
              listType={fields.listType}
              onChange={(ids, lists) => {
                form.updateFields({ [fields.domkey[0]]: { value: `${ids}` } }, false);
              }}
              datas={fields.datas || []}
            />);
          } else {
            dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@1wimo6@${index}`} fieldConfig={fields} form={form} />;
          }
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@gj3ouo@${index}`}
              label={`${fields.label}`}
              error={form.getError(fields)}
              tipPosition="bottom"
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              underline={isunderline}
            >
              {dom}
            </WeaFormItem>),
            colSpan: 1,
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@br75sk@${indexGroup}`} needTigger col={1} title={c.title} showGroup={c.defaultshow} items={items} />);
      });
      return group;
    }
    getEditForms() {
      const { formCondition, form } = this.props.contentStore;
      const { isFormInit } = form;
      const group = [];
      const formParams = form.getFormParams();
      isFormInit && toJS(formCondition).map((c,indexGroup) => {
        const items = [];
        c.items.map((fields, index) => {
          const oldValue = fields.value;
          let dom;
          let isunderline = '';
          if (fields.viewAttr == '1' || (fields.conditionType == 'BROWSER' && fields.browserConditionParam.viewAttr == '1')) { fields.hasBorder = false; isunderline = 'underline'; } // 只读样式控制
          if (fields.conditionType == 'INPUT' || fields.conditionType == 'TEXTAREA') {
            dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@22jwbf@${index}`} fieldConfig={fields} form={form} onBlur={(v) => { this.onEditChange2(oldValue, fields, v); }} />;
          } else if (fields.conditionType == 'ATTACHEMENT') {
            const key = getKey(fields);
            const bindObj = form.$(key);
            dom = (<WeaUpload
              ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@4ugvp3@${index}`}
              {...bindObj.bind()}
              {...fields}
              {...fields.otherParams}
              uploadId={fields.domkey[0]}
              uploadUrl="/api/crm/common/fileUpload"
              category="0,0,0"
              autoUpload
              showBatchLoad={false}
              showClearAll={false}
              multiSelection
              listType={fields.listType}
              onChange={(ids, lists) => {
                form.updateFields({ [fields.domkey[0]]: { value: `${ids}` } }, false);
                this.onEditChange2(oldValue, fields, `${ids}`);
              }}
              datas={fields.datas || []}
            />);
          } else {
            dom = <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@kxnt59@${index}`} fieldConfig={fields} form={form} onChange={this.onEditChange.bind(this, oldValue, fields)} />;
          }
          items.push({
            com: (<WeaFormItem
              ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@fvrz0f@${index}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              underline={isunderline}
            >
              <WeaError
                ecId={`${this && this.props && this.props.ecId || ''}_WeaError@qockcv@${index}`}
                tipPosition="bottom"
                style={{ width: '100%' }}
                ref={fields.domkey[0]}
                error={`${'"' + `${fields.label}` + '"'}${getLabel(21423, '未填写')}`}
              >
                {dom}
              </WeaError>
            </WeaFormItem>),
            colSpan: 1,
          });
        });
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@ag4x7e@${indexGroup}`} needTigger col={1} title={c.title} showGroup={c.defaultshow} items={items} />);
      });
      return group;
    }

    onEditChange(oldvalue = '', field, res) {
      const { customerId, saveEditAddress, addressId, formCondition, form } = this.props.contentStore;
      const fit = field.conditionType.toUpperCase();
      const fieldName = field.domkey[0];
      const value = res[fieldName].value;
      if (value !== oldvalue) {
        if (field.viewAttr == 3 && value == '') {
          this.refs[fieldName].showError();
          setTimeout(() => {
            form.initFormFields(formCondition);
          }, 100);
          return false;
        }
        const params = {
          customerId,
          addressId,
          fieldname: fieldName,
          oldvalue,
          newvalue: value,
          fieldtype: fit,
        };
        saveEditAddress(params);
      }
    }
    resetEmail = (conditioninfo, fieldName, fieldValue) => {
      for (let i = 0; i < conditioninfo.length; i++) {
        const items = conditioninfo[i].items;
        for (let j = 0; j < items.length; j++) {
          const item = items[j];
          const name = item.domkey[0];
          if (fieldName == name) {
            item.value = fieldValue;
          }
        }
      }
    }
    onEditChange2 = (oldvalue = '', field, value) => {
      const { customerId, saveEditAddress, addressId, formCondition, form } = this.props.contentStore;
      const fit = field.conditionType.toUpperCase();
      const fieldName = field.domkey[0];
      if (value !== oldvalue) {
        if (field.viewAttr == 3 && value == '') {
          this.refs[fieldName].showError();
          setTimeout(() => {
            form.initFormFields(formCondition);
          }, 100);
          return false;
        } else if (fieldName == 'email' && value != '' && !isEmail(value)) {
          setTimeout(() => {
            form.initFormFields(formCondition);
          }, 100);
          message.error(getLabel(71, '邮件') + getLabel(15196, '格式') + getLabel(127353, '错误'));
          return false;
        }
        const params = {
          customerId,
          addressId,
          fieldname: fieldName,
          oldvalue,
          newvalue: value,
          fieldtype: fit,
        };
        saveEditAddress(params);
      }
    }
}


export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@8m7we7`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(AddressManage);
